<html>
<head>
    <title>前端客户端</title>
    <link href="./bootstrap.min.css" rel="stylesheet" />
    <script type="text/javascript" src="./jquery-3.5.1.min.js"></script>
    <script src="./bootstrap.min.js"></script>
    <script type="text/javascript" src="./signalr.min.js"></script>
    <script type="text/javascript" src="./message.js"></script>
</head>
<body>
    <div class="col-md-5">
        <div class="col-md-12">
            <label for="inputMessage">请输入消息内容</label>
        </div>
        <div class="col-md-8">
            <input type="text"
                   id="inputMessage"
                   class="form-control"
                   placeholder="请输入消息内容:" />
        </div>
        <div class="col-md-4">
            <input type="button"
                   id="inputSubmit"
                   value="发送"
                   class="btn btn-primary"
                   onclick="onButtonClick(this)" />
        </div>
    </div>
    <div class="col-md-6">
        <div class="row">
            <label for="messages">这里是历史消息记录</label>
        </div>
        <div class="row">
            <textarea id="messages"
                      rows="10"
                      class="form-control"
                      placeholder="还没有收到消息.."></textarea>
        </div>
    </div>

    <script type="text/javascript">
        var client = new MessageClient(
            "ws://mc.devonline.cn/message",
            "js client"
        );

        client.on("Receive", (message) => {
            if (message && message.content) {
                //console.log(`收到了来自 ${message.sender} 的消息: ` + message.content);
                var content = message.content;
                try {
                    var order = JSON.parse(message.content);
                    content = `订单编号: ${order.id}, 金额为: ${order.amount}`;
                } catch (e) {
                    console.log('消息内容不是订单, 无法转化为订单消息');
                }

                $("#messages").append(
                    `收到了 ${message.sender} 的消息, 内容为: ${content}\n`
                );
            }
        });

        client.start();

        var receiver = "asp.net core web server side";

        function clearInput() {
            $("#inputMessage").val("");
        }

        function onButtonClick(e) {
            var content = $("#inputMessage").val();
            if (content) {
                client.send(content, receiver, null, clearInput, clearInput);
                $("#messages").append(
                    `发送给 ${receiver} 的消息, 内容为: ${content}\n`
                );
            }
        }
    </script>
</body>
</html>
